package stack_queue.p1_stack.arraystack;

import java.util.Stack;

public class Test {
    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
        test4();
    }

    public static boolean isPopOrder(int[] pushV, int[] popV) {
        int lenA = pushV.length;
        int lenB = popV.length;
        if (lenA != lenB) return false;
        Stack<Integer> s = new Stack<>();
        for (int i = 0, j = 0; j < lenA; ) {
            if (s.isEmpty() || s.peek() != popV[j]) {
                if (i >= lenA) break;
                s.push(pushV[i++]);
            }
            if (s.peek() == popV[j]) {
                s.pop();
                j++;
            }
        }
        return s.isEmpty();
    }

    private static void test3() {
        int[] arr = {1, 2, 3, 4, 5};
        int[] brr = {4, 5, 3, 2, 1};
        System.out.println(isPopOrder(arr, brr));
    }

    public static int evalRPN(String[] tokens) {
        Stack<Integer> number = new Stack<>();
        for (String token : tokens) {
            char ch = token.charAt(0);
            if (token.length() == 1 && "+-*/".indexOf(ch) != -1) {
                int a = number.pop();
                int b = number.pop();
                int ret = switch (ch) {
                    case '+' -> b + a;
                    case '-' -> b - a;
                    case '*' -> b * a;
                    case '/' -> b / a;
                    default -> throw new IllegalArgumentException("Invalid operator");
                };
                number.push(ret);
            } else {
                number.push(Integer.parseInt(token));
            }
        }
        return number.pop();
    }


    private static void test4() {
        String[] str = {"2","1","+","3","*"};
        System.out.println(evalRPN(str));
    }

    public static boolean parenthesesMatch(String str) {
        Stack<Character> s = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == '{' || ch == '[' || ch == '(') {
                s.push(ch);
            }
            if (ch == '}' || ch == ']' || ch == ')') {
                if (s.isEmpty()) {
                    return false;
                }
                char top = s.pop();
                if (top == '{' && ch != '}' || top == '[' && ch != ']' || top == '(' && ch != ')') {
                    return false;
                }
            }
        }
        return s.isEmpty();
    }

    private static void test2() {
        String str = "(";
        System.out.println(parenthesesMatch(str));
    }

    private static void test1() {
        ArrayStack as = new ArrayStack();
        as.push(1);
        as.push(2);
        as.push(3);
        System.out.println(as.getSize());
        System.out.println(as.peek());
        System.out.println(as.pop());
        System.out.println(as.pop());
        System.out.println(as.pop());
    }
}
